//
//  LoginViewController.m
//  GC_OC
//
//  Created by Tianbao Wang on 2022/5/26.
//

#import "LoginViewController.h"
#import "AppleIDLoginUtils.h"
#import "RegisterViewController.h"
#import "UserLoginViewController.h"
#import "UserModel.h"
#import "Cache.h"
#import "MineViewController.h"

@interface LoginViewController ()
@property(nonatomic, strong) UIView *navigationBarView;
@property (nonatomic, strong) ObjectAFNetWorking* objectAFNet;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.objectAFNet = [ObjectAFNetWorking new];
    [self setupUIView];
}

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:true animated:true];
//    
//}
//
//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    [self.navigationController setNavigationBarHidden:false animated:true];
//    
//}

- (void)back {
    NSInteger childCount = self.navigationController.viewControllers.count;
    if (childCount > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
//        UIViewController *vc = self.navigationController.presentedViewController;
        [self.navigationController dismissViewControllerAnimated:true completion:nil];
    }
    
    if (self.navigationController.viewControllers.count == 1) {
        if ([ICMusicPlayManager sharedManager].narrowView) {
            [ICMusicPlayManager sharedManager].narrowView.frame = CGRectMake(0, SCREEN_HEIGHT - 50 - GCtabbarHeight, SCREEN_WIDTH, 50);
        }
    }
}

- (void)loginAct {
    [self.navigationController pushViewController:[UserLoginViewController new] animated:YES];
}

- (void)regAct {
    [self.navigationController pushViewController:[RegisterViewController new] animated:YES];
}

- (void)appleidAct {
    if (@available(iOS 13.0, *)) {
        [[AppleIDLoginUtils shared] authrization:^(ASAuthorizationAppleIDCredential * credential, NSError * err) {
            if (credential.user) {
                NSString *idtoken = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding];
                NSLog(@"credential~~>>%@",credential.user);
                NSString *apple_user = credential.user;
                
                NSString *email = credential.email;
                
                NSArray<ASAuthorizationScope> *authorizedScopes = credential.authorizedScopes;
                // refresh_token
                NSString *authorizationCode = [[NSString alloc] initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding];
                // access_token
                NSString *identityToken = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding];
                NSPersonNameComponents *fullName = credential.fullName;
                ASUserDetectionStatus realUserStatus = credential.realUserStatus;
                
                NSString *name = nil;
                if(fullName.givenName && fullName.familyName) {
                    name = [NSString stringWithFormat:@"%@%@", fullName.familyName, fullName.givenName];
                } else {
                    name = @"";
                }
                
                if(email == NULL) {
                    email = @"";
                }
                
                
                [self appleLogin:idtoken apple_user:apple_user email:email name:name];
            }
        }];
    } else {
        // Fallback on earlier versions
        [SVProgressHUD showInfoWithStatus:@"当前系统版本不支持appleid登录"];
    }
}

- (void)appleLogin:(NSString *)token apple_user:(NSString *)apple_user email:(NSString *)email name:(NSString *)name {
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *p = [[NSMutableDictionary alloc]init];
    p[@"apple_user"] = apple_user;
    p[@"uid"] = token;
    p[@"version"] = UIApplication.sharedApplication.fk_appVersion;
    p[@"email"] = email;
    p[@"name"] = name;
    [SVProgressHUD show];
    [FKHttpTool postWithSuffix:@"/api/user/AppleAuthLogin" param:p success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD dismiss];
            // 这里后台返回的字段错了，因此特殊处理一下，本应该返回userinfo的，结果返回的user
            if ([result.data[@"user"] isKindOfClass:[NSDictionary class]]) {
                NSMutableDictionary *temp = [NSMutableDictionary dictionaryWithDictionary:result.data];
                temp[@"userinfo"] = result.data[@"user"];
                result.data = temp;
            }
            UserModel *user = [UserModel mj_objectWithKeyValues:result.data];
            
            [Cache shared].userInfo = user;
            [FKCacheTool saveUserInfo:result.data];
            [FKCacheTool saveToken:user.userinfo.token];
            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
            
            [self.navigationController dismissViewControllerAnimated:true completion:^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccess" object:nil userInfo:nil];
            }];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.view makeToast:error.debugDescription];
    }];
//    [self.objectAFNet postUrlStr:[NSString stringWithFormat:@"%@/api/user/AppleAuthLogin",server_addr] parames:p finish:^(id  _Nonnull dataString) {
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"dicdic~~>>%@",dic);
//        if ([dic[@"code"] isEqual:@200]) {
//            NSError *err;
//            UserModel *user = [[UserModel alloc] initWithDictionary:dic[@"data"] error:&err];
//            [Cache shared].userInfo = user;
//            [Cache shared].userInfo = user;
//            [FKCacheTool saveToken:user.userinfo.token];
//
//            NSMutableArray *vcs = [[NSMutableArray alloc] init];
//            for (int i=0; i<self.navigationController.viewControllers.count; i++) {
//                UIViewController *control = self.navigationController.viewControllers[i];
//                [vcs addObject:control];
//                if ([control isKindOfClass:[LoginViewController class]]) {
//                    [vcs removeObject:control];
//                    break;
//                }
//            }
//            MineViewController *mine = [MineViewController new];
//            mine.hidesBottomBarWhenPushed = YES;
//            [vcs addObject:mine];
//            [self.navigationController setViewControllers:vcs animated:YES];
//
//            if (self->_isplayskip == 100) {
//                [[GCAVPlayer shared] showpppLoginplayer];
//            }
//
//        }
//    } andError:^(NSError * _Nonnull error) {
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//
//    }];
}

- (void)setupUIView {
    self.view.backgroundColor = UIColor.whiteColor;
    
    UIImageView *bgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_bg"]];
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.navigationBarView = [UIView new];
    self.navigationBarView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.navigationBarView];
    [self.navigationBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(NAVI_BAR_HIGHT);
    }];
    
    UIButton *backButton = [UIButton new];
    [backButton setImage:[UIImage imageNamed:@"icon_清空_32_default"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:backButton];
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(32);
        make.left.equalTo(self.view).offset(12);
        make.top.mas_equalTo(StatusBarHeight + 4);
    }];
    
    UIImageView *logoView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo"]];
    [self.view addSubview:logoView];
    [logoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(125);
    }];
    
    UIImageView *alertView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_appleid_alert"]];
    [self.view addSubview:alertView];
    [alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(logoView.mas_bottom).offset(66);
    }];
    
    UILabel *msgLabel = [[UILabel alloc] init];
    msgLabel.text = @"点击登陆，享受更多权益";
    msgLabel.textColor = XHUIColorFromRGB(0x0091FF);
    msgLabel.font = [UIFont systemFontOfSize:14];
    [alertView addSubview:msgLabel];
    [msgLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(alertView).offset(5);
        make.centerX.equalTo(alertView);
    }];
    
    UIButton *appleButton = [UIButton new];
    appleButton.clipsToBounds = YES;
    appleButton.layer.cornerRadius = 28;
    appleButton.backgroundColor = XHUIColorFromRGB(0x0091FF);
    [appleButton setTitle:@"   Apple ID 快捷登陆" forState:UIControlStateNormal];
    [appleButton setImage:[UIImage imageNamed:@"login_apple_logo"] forState:UIControlStateNormal];
    appleButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC" size: 16];
    [appleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [appleButton addTarget:self action:@selector(appleidAct) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:appleButton];
    [appleButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(56);
        make.right.equalTo(self.view).offset(-50);
        make.left.equalTo(self.view).offset(50);
        make.top.equalTo(logoView.mas_bottom).offset(134);
    }];
    
    UIButton *loginButton = [UIButton new];
    [loginButton setTitle:@"账号登陆" forState:UIControlStateNormal];
    loginButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC" size: 16];
    [loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(loginAct) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginButton];
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_centerX).offset(-17);
        make.bottom.equalTo(self.view).offset(-106 - HY_BottomWhiteBar_Height);
    }];
    
    UIButton *regButton = [UIButton new];
    [regButton setTitle:@"注册用户" forState:UIControlStateNormal];
    regButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC" size: 16];
    [regButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [regButton addTarget:self action:@selector(regAct) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:regButton];
    [regButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_centerX).offset(17);
        make.bottom.equalTo(self.view).offset(-106 - HY_BottomWhiteBar_Height);
    }];
}
@end
